package com.ffcc.fitness.websocket.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.ffcc.fitness.websocket.handler.SpringChatWebSocketHandler;
import com.ffcc.fitness.websocket.mapper.ChatMapper;
import com.ffcc.fitness.websocket.mapper.MessageMapper;
import com.ffcc.fitness.websocket.pojo.Chat;
import com.ffcc.fitness.websocket.pojo.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 聊天服务类
 */
@Service
public class ChatService {
    
    @Autowired
    private MessageMapper messageMapper;
      @Autowired
    private ChatMapper chatMapper;
    
    // ObjectMapper用于序列化消息
    private final ObjectMapper objectMapper;
    
    public ChatService() {
        this.objectMapper = new ObjectMapper();
        this.objectMapper.registerModule(new JavaTimeModule());
        this.objectMapper.disable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    }
      /**
     * 发送消息
     */    public Message sendMessage(Long fromId, Long toId, String content) {
        System.out.println("=== ChatService.sendMessage 被调用 ===");
        System.out.println("发送者ID：" + fromId + "，接收者ID：" + toId);
        System.out.println("消息内容长度：" + (content != null ? content.length() : 0));
        if (content != null && content.length() > 100) {
            System.out.println("消息内容（前100字符）：" + content.substring(0, 100) + "...");
        } else {
            System.out.println("消息内容：" + content);
        }
        
        // 创建消息
        Message message = new Message();
        message.setFromId(fromId);
        message.setToId(toId);
        message.setContent(content);
        message.setReadStatus(0);
        message.setCreateTime(LocalDateTime.now());
        message.setUpdateTime(LocalDateTime.now());
          // 保存消息
        messageMapper.insert(message);
        System.out.println("消息已保存到数据库，消息ID：" + message.getMessageId());
        
        // 创建或更新会话
        createOrUpdateSession(fromId, toId, message.getMessageId());
        System.out.println("会话已创建或更新");
        
        // 通过WebSocket推送消息给接收者
        try {
            System.out.println("=== 开始WebSocket推送 ===");
            if (SpringChatWebSocketHandler.isUserOnline(toId)) {
                System.out.println("用户 " + toId + " 在线，准备推送消息");
                String messageJson = objectMapper.writeValueAsString(message);
                System.out.println("消息JSON：" + messageJson);
                SpringChatWebSocketHandler.sendMessageToUser(toId, messageJson);
                System.out.println("消息已通过WebSocket发送给用户: " + toId);
            } else {
                System.out.println("接收者用户 " + toId + " 不在线，消息已保存到数据库");
            }
        } catch (Exception e) {
            System.err.println("WebSocket消息推送失败: " + e.getMessage());
            e.printStackTrace();
            // 不抛出异常，确保消息至少保存到了数据库
        }
        
        return message;
    }
    
    /**
     * 获取聊天记录
     */
    public List<Message> getChatHistory(Long userId, Long otherUserId, Integer limit) {
        return messageMapper.getChatHistory(userId, otherUserId, limit);
    }
    
    /**
     * 标记消息为已读
     */
    public void markAsRead(Long fromId, Long toId) {
        messageMapper.markAsRead(fromId, toId);
          // 清零会话未读数
        Chat session = findSession(fromId, toId);
        if (session != null) {
            chatMapper.clearUnread(session.getSessionId(), toId);
        }
    }
    
    /**
     * 获取用户的未读消息数
     */
    public int getUnreadCount(Long userId) {
        return messageMapper.getUnreadCount(userId);
    }
    
    /**
     * 获取用户的会话列表
     */
    public List<Chat> getUserSessions(Long userId) {
        return chatMapper.getUserSessions(userId);
    }
    
    /**
     * 创建或获取聊天会话（用于联系卖家功能）
     */    public Chat createOrGetChat(Long buyerId, Long sellerId, Long equipmentId, String equipmentTitle) {
        // 确保user1Id < user2Id
        Long user1Id = Math.min(buyerId, sellerId);
        Long user2Id = Math.max(buyerId, sellerId);
        
        Chat session = chatMapper.findSession(user1Id, user2Id);
        
        if (session == null) {
            // 创建新会话
            session = new Chat();
            session.setUser1Id(user1Id);
            session.setUser2Id(user2Id);
            session.setLastMsgId(null);
            session.setLastTime(LocalDateTime.now());
            session.setUser1Unread(0);
            session.setUser2Unread(0);
            session.setCreateTime(LocalDateTime.now());
            session.setUpdateTime(LocalDateTime.now());
            
            chatMapper.insert(session);
            
            // 发送一条初始消息
            String initialMessage = "你好，我对【" + equipmentTitle + "】感兴趣，请问还在吗？";
            sendMessage(buyerId, sellerId, initialMessage);
        }
        
        return session;
    }

    /**
     * 创建或更新会话
     */
    private void createOrUpdateSession(Long fromId, Long toId, Long messageId) {
        // 确保user1Id < user2Id
        Long user1Id = Math.min(fromId, toId);
        Long user2Id = Math.max(fromId, toId);
        
        Chat session = chatMapper.findSession(user1Id, user2Id);
        
        if (session == null) {
            // 创建新会话
            session = new Chat();
            session.setUser1Id(user1Id);
            session.setUser2Id(user2Id);
            session.setLastMsgId(messageId);
            session.setLastTime(LocalDateTime.now());
            session.setUser1Unread(toId.equals(user1Id) ? 1 : 0);
            session.setUser2Unread(toId.equals(user2Id) ? 1 : 0);
            session.setCreateTime(LocalDateTime.now());
            session.setUpdateTime(LocalDateTime.now());
            
            chatMapper.insert(session);        } else {
            // 更新现有会话
            chatMapper.updateLastMessage(session.getSessionId(), messageId);
            // 增加接收者的未读数
            chatMapper.incrementUnread(session.getSessionId(), toId);
        }
    }
      /**
     * 查找会话
     */
    private Chat findSession(Long userId1, Long userId2) {
        Long user1Id = Math.min(userId1, userId2);
        Long user2Id = Math.max(userId1, userId2);
        return chatMapper.findSession(user1Id, user2Id);
    }
}
